import { t } from 'i18next'
import React, { useEffect, useState } from 'react'
import { Button, Select, Space, Search, InputNumber } from '@kedacom/react-next'
import { StyledPollModal } from './style'
import { Alert } from '@/components/Alert'
import { useDebounceEffect, useRequest } from 'ahooks'
import { Poll } from '@/pages/manager/blocks/vmp/interface'
import { fetchGetPollPlanDetail, fetchGetPollPlanList } from '@/api/manager/poll'
import { useMccStore } from '@/pages/manager/store'
import shallow from 'zustand/shallow'
import { ListItem } from './listItem'
import { ListItem as SelectedListItem } from './selectedIistItem'
import AutoSizer from 'react-virtualized-auto-sizer'
import { FixedSizeList as List, ListChildComponentProps } from 'react-window'
import { isCascadeTree } from '@/pages/manager/blocks/main/table/all/utils'
import { ItemData, SelectedModel, useSinglePollStore } from './store'
import { IconTips } from '@/components/List/ListEmpty/style'
import { useTableOftenStore } from '@/pages/manager/blocks/main/table/often/store'
import { useTableAllStore } from '@/pages/manager/blocks/main/table/all/store'
import { useTableInteractiveStore } from '@/pages/manager/blocks/main/table/interactive/store'
import { listOrderClick } from '@/utils/listSlice'
import { useGlobalStore } from '@/store/global'

export interface PollModalProps {
	data: SinglePollData
	setOpen: (open: boolean) => void
	getPollMembersNum: () => number
	okCallBack: (data: SinglePollData) => void
}
export type SinglePollData = {
	/**第几个框 */
	index: number
	poll: Poll | null
}
const intervalOptions = [
	{ label: t('快（15秒）'), value: 15 },
	{ label: t('中（30秒）'), value: 30 },
	{ label: t('慢（60秒）'), value: 60 },
	{ label: t('自定义'), value: 0 },
]
interface RowRendererProps extends ListChildComponentProps {
	data: { list: ItemData[]; isCascade: boolean }
}
const rowRenderer = React.memo(({ data, index, style }: RowRendererProps) => {
	const rowData = data.list[index]
	return (
		<div style={style}>
			<ListItem isCascade={data.isCascade} {...rowData} />
		</div>
	)
})
interface RowRendererPropsS extends ListChildComponentProps {
	data: SelectedModel[]
}
const rowRendererS = React.memo(({ data, index, style }: RowRendererPropsS) => {
	const rowData = data[index]
	return (
		<div style={style}>
			<SelectedListItem {...rowData} />
		</div>
	)
})
export default function PollModal(props: PollModalProps) {
	const { data, setOpen, getPollMembersNum, okCallBack } = props
	const { meetingMoid, superMtNum } = useMccStore(
		(state) => ({
			meetingMoid: state.mccInfo.meetingMoid,
			superMtNum: state.mccInfo.superMtNum,
		}),
		shallow
	)
	const {
		list,
		tab,
		selectedList,
		getListFromTableAll,
		getListFromTable,
		update,
		addAllToRight,
		addAllSelectedToRight,
		removeSelectedCheckedItem,
		removeAllSelectedItem,
		mtChange2SelectedItem,
	} = useSinglePollStore(
		(state) => ({
			tab: state.tab,
			list: state.list,
			selectedList: state.selectedList,
			getListFromTableAll: state.getListFromTableAll,
			getListFromTable: state.getListFromTable,
			update: state.update,
			addAllToRight: state.addAllToRight,
			addAllSelectedToRight: state.addAllSelectedToRight,
			removeSelectedCheckedItem: state.removeSelectedCheckedItem,
			removeAllSelectedItem: state.removeAllSelectedItem,
			mtChange2SelectedItem: state.mtChange2SelectedItem,
		}),
		shallow
	)
	const [searchVal, setSearchVal] = useState('')
	const [actualSearchVal, setActualSearchVal] = useState('')
	const handleSearch = (val: string) => {
		setSearchVal(val)
	}
	useDebounceEffect(
		() => {
			setActualSearchVal(searchVal)
		},
		[searchVal],
		{
			wait: 250,
		}
	)
	const [pollPreValue, setPollPreValue] = useState('0')
	const [pollTimeValue, setPollTimeValue] = useState(30)
	const [inputValue, setInputValue] = useState('5')
	const [planOptions, setPlanOptions] = useState<Array<{ label: string; value: string }>>([
		{ label: t('不使用预案'), value: '0' },
	])
	const { data: pollData } = useRequest(() => fetchGetPollPlanList(meetingMoid))
	useEffect(() => {
		if (pollData && pollData.success) {
			let arr = pollData.data ? pollData.data.map((item) => ({ label: item.name, value: item.id })) : []
			arr.unshift({ label: t('不使用预案'), value: '0' })
			setPlanOptions(arr)
		}
	}, [pollData])

	const initData = (data: Poll | null) => {
		if (data) {
			let arr = data.members.map(
				(x) =>
					({
						mcc: x,
						mtKey: x.mtKey,
						status: {
							checked: false,
						},
					} as unknown as SelectedModel)
			)
			update({ selectedList: arr })
			setPollPreValue(planOptions.find((item) => item.label === data.name)?.value ?? '0')
			if ([15, 30, 60].indexOf(data.keep_time) !== -1) {
				setPollTimeValue(data.keep_time)
			} else {
				setPollTimeValue(0)
				setInputValue(String(data.keep_time))
			}
		} else {
			update({ selectedList: [] })
			setPollPreValue('0')
			setPollTimeValue(30)
			setInputValue('5')
		}
	}
	useEffect(() => {
		initData(data.poll)
	}, [data.poll])
	const changePollPreOption = (id: string) => {
		if (id === '0') {
			initData(null)
			return
		}
		fetchGetPollPlanDetail(meetingMoid, id).then((res) => {
			if (res.success) {
				initData(new Poll(res))
			} else {
				Alert(t('获取轮询预案失败'))
			}
		})
	}
	const tableAll = useTableAllStore((state) => state.tree)
	const tableOften = useTableOftenStore((state) => state.list)
	const tableInteractive = useTableInteractiveStore((state) => state.list)
	const isCascade = isCascadeTree(tableAll)
	useEffect(() => {
		if (superMtNum === 0 && tab === 'all') {
			getListFromTableAll(tableAll, actualSearchVal)
		}
	}, [tableAll, tab, actualSearchVal, superMtNum])
	useEffect(() => {
		if (superMtNum === 0 && tab === 'often') {
			getListFromTable(tableOften, actualSearchVal)
		}
	}, [tableOften, tab, actualSearchVal, superMtNum])
	useEffect(() => {
		if (superMtNum === 1) {
			update({ tab: 'interactive' })
			getListFromTable(tableInteractive, actualSearchVal)
		}
	}, [tableInteractive, actualSearchVal, superMtNum])

	useEffect(() => {
		mtChange2SelectedItem()
	}, [tableAll])

	const SWITCH = useGlobalStore((state) => state.SWITCH)

	const okFn = () => {
		if (pollTimeValue === 0) {
			if (!inputValue) {
				Alert(t('请设置轮询间隔'))
				return
			} else if (Number(inputValue) < 5 || Number(inputValue) > 7200) {
				Alert(t('自定义间隔时间范围为5~7200'))
				return
			}
		}
		if (selectedList.length === 0) {
			Alert(t('请选择轮询终端'))
			return
		}
		if (getPollMembersNum() + selectedList.length > 750) {
			Alert(t('轮询终端数超限'))
			return
		}
		setOpen(false)
		reset()
		let plan = planOptions.find((item) => item.value === pollPreValue)
		okCallBack({
			index: data.index,
			poll: {
				...data.poll,
				id: plan?.value === '0' ? '' : plan?.value ?? '',
				name: plan?.value === '0' ? '' : plan?.label ?? '',
				members: selectedList.map((x) => x.mcc) as any[],
				keep_time: pollTimeValue !== 0 ? pollTimeValue : Number(inputValue),
				num: 0,
				mode: 1,
			},
		})
	}
	const reset = () => {
		// setPollPreValue('0')
		// setPollTimeValue(30)
		// setInputValue('5')
		// setSearchVal('')
		// setActualSearchVal('')
	}

	const handleOrder = (type: 'top' | 'up' | 'down' | 'bottom') => {
		const result = listOrderClick(selectedList, type)
		update({ selectedList: result })
	}

	return (
		<StyledPollModal className="simple-poll-modal__i18n" superMtNum={!!superMtNum || !SWITCH.showOftenMt ? 1 : 0}>
			<div className="poll-plan-wrap">
				<div className="poll-plan">
					<span className="poll-label">{t('轮询预案')}</span>
					<Select
						width={248}
						options={planOptions}
						value={pollPreValue}
						onClick={(e, value) => changePollPreOption(value)}
					/>
				</div>
				<div className="poll-interval">
					<span className="poll-label">{t('轮询间隔')}</span>
					<Select
						// width={80}
						options={intervalOptions}
						value={pollTimeValue}
						onChange={(e, value) => setPollTimeValue(value)}
					/>
					<div className={`seconds ${pollTimeValue === 0 ? '' : 'hide'}`}>
						<InputNumber
							width={60}
							className="seconds-input"
							maxLength={4}
							value={inputValue}
							onChange={(e, value) => {
								setInputValue(value)
							}}
						/>
						<span>{t('5~7200秒')}</span>
					</div>
				</div>
			</div>
			<div className="transfer-wrap">
				<div className="left-list">
					{superMtNum === 0 && !!SWITCH.showOftenMt && (
						<div className="tab">
							<span
								className={`${tab === 'all' ? 'selected' : ''}`}
								onClick={() => update({ tab: 'all' })}
							>
								{t('全部终端')}
							</span>
							<span
								className={`${tab === 'often' ? 'selected' : ''}`}
								onClick={() => update({ tab: 'often' })}
							>
								{t('常用终端')}
							</span>
						</div>
					)}
					<div className="content">
						<Search
							className="content-search"
							iconAlign="left"
							placeholder={t('请输入关键词搜索')}
							value={searchVal}
							onChange={(e, val) => handleSearch(val)}
							onClear={() => handleSearch('')}
							clearable
						/>
						<div className="member-list">
							<AutoSizer>
								{({ width, height }) => {
									return (
										<List
											width={width}
											height={height}
											itemCount={list.length}
											itemSize={38}
											itemData={{ list, isCascade }}
											itemKey={(index, data) => data.list[index].mtKey}
										>
											{rowRenderer}
										</List>
									)
								}}
							</AutoSizer>
						</div>
					</div>
				</div>
				<div className="transfer-operate">
					<span className="btn all-right" onClick={() => addAllToRight()} />
					<span className="btn right" onClick={() => addAllSelectedToRight()} />
					<span className="btn left" onClick={() => removeSelectedCheckedItem()} />
					<span className="btn all-left" onClick={() => removeAllSelectedItem()} />
				</div>
				<div className="right-list">
					<div className="title">{t('已选 {{num}} 位', { num: selectedList.length })}</div>
					<div className="content">
						<div className="member-list">
							<AutoSizer>
								{({ width, height }) => {
									return (
										<List
											width={width}
											height={height}
											itemCount={selectedList.length}
											itemSize={38}
											itemData={selectedList}
											itemKey={(index, data) => data[index].mtKey}
										>
											{rowRendererS}
										</List>
									)
								}}
							</AutoSizer>
						</div>
					</div>
				</div>
				<div className="right-operate">
					<span className="btn top" onClick={() => handleOrder('top')} />
					<span className="btn up" onClick={() => handleOrder('up')} />
					<span className="btn down" onClick={() => handleOrder('down')} />
					<span className="btn bottom" onClick={() => handleOrder('bottom')} />
				</div>
			</div>
			<div className="footer">
				<span className="msg">
					<IconTips className="icon-tips" />
					{t('可使用ctrl或shift快捷键进行多选')}
				</span>
				<Space>
					<Button onClick={okFn}>{t('确定')}</Button>
					<Button onClick={() => setOpen(false)}>{t('取消')}</Button>
				</Space>
			</div>
		</StyledPollModal>
	)
}
